import requests
import csv, time

##### 作业1：
##### 获取网页地址，及利用 requests 库的 get 方法获取 json 格式的 “肖申克的救赎” 电影所有数据
def download_image(url_image,name):
    ##### 这种多媒体文件我们需要用二进制来处理
    url_1=requests.get(url_image,headers={'user-agent':'chrome'})
    ##### 这种多媒体文件我们需要用二进制来处理，所以不再是 .text，而是用 .content。这个拿到的是原始的二进制信息
    with open('%s.jpg'%name,'wb') as f:
        f.write(url_1.content)
        print('ok')

url='https://api.douban.com/v2/movie/1292052?apikey=0df993c66c0c636e29ecbb5344252a4a'
r_get = requests.get(url, headers={'user-agent': 'chrome'})
r_json = r_get.json()
url_image = r_json.get('image')
name = r_json.get('title')
url_1 = requests.get(url_image, headers={'user-agent': 'chrome'})
#调用函数
download_image(url_image,name)

##### 作业2：
def top_250(start=0):
    result=[]
    while start<250:
        url='https://api.douban.com/v2/movie/top250?start=%d&apikey=0df993c66c0c636e29ecbb5344252a4a'%start
        time.sleep(2)
        r_get=requests.get(url,headers={'user-agent':'chrome'})
        r_json=r_get.json()
        start=int(r_json['start'])+int(r_json['count'])
        with open('douban.csv', 'a') as f:
            f_csv = csv.writer(f)
            for item in r_json['subjects']:
                casts = ','.join(j['name'] for j in item['casts'])
                images = item['images']['large']
                line = [item['id'], item['title'], item['rating']['average'], casts, images]
                result.append(line)
                f_csv.writerow(line)
    return result
results=top_250(0)

##### 作业3：
for i in results:
    url_image=i[-1]
    name=i[0]
    download_image(url_image,name)
    time.sleep(2)